package com.yanceysong.snake.database;

import com.yanceysong.snake.StartSnakeGameApplication;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class JdbcUtil {

    /**
     * 文件的读取，只需要读取一次即可拿到这些值。使用静态代码块
     */
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 获取连接
     *
     * @return 连接对象
     */
    public static Connection getConnection() {
        try {
            return DriverManager.getConnection("jdbc:mysql://%s:3306/snake?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false"
                    .formatted(StartSnakeGameApplication.address)
                    , StartSnakeGameApplication.username
                    , StartSnakeGameApplication.password);
        } catch (SQLException e) {

            return null;
        }
    }

    /**
     * 释放资源
     *
     * @param stmt Statement
     * @param conn Connection
     */
    public static void close(Statement stmt, Connection conn) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    @SneakyThrows
    public static void close(Connection connection) {
        if (connection != null) {
            connection.close();
        }
    }

    /**
     * 释放资源
     *
     * @param stmt Statement
     * @param conn 数据库连接
     */
    @SneakyThrows
    public static void close(ResultSet rs, Statement stmt, Connection conn) {
        if (rs != null) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
        if (conn != null) {
            conn.close();
        }
    }
}
